﻿using System;
using System.Linq;
using System.IO;
using System.IO.IsolatedStorage;
using System.Collections.Generic;
using Microsoft.LightSwitch;
using Microsoft.LightSwitch.Framework.Client;
using Microsoft.LightSwitch.Presentation;
using Microsoft.LightSwitch.Presentation.Extensions;
namespace LightSwitchApplication
{
    public partial class EntitiesListDetail
    {
        partial void EntityListAddAndEditNew_CanExecute(ref bool result)
        {
            // Write your code here.

        }

        partial void EntityListAddAndEditNew_Execute()
        {
            Entity newEntity = Entities.AddNew();
            newEntity.Schema = "dbo";

            Field rowId = newEntity.Fields.AddNew();
            rowId.Name = "RowId";
            rowId.DataType = "uniqueidentifier";
            rowId.Nullable = false;
            rowId.PrimaryKey = true;
            rowId.SortOrder = 1;
            rowId.Description = "Default GUID";
            Entities.SelectedItem = newEntity;
        }

        partial void FieldsAddNew_CanExecute(ref bool result)
        {
            // Write your code here.

        }

        partial void FieldsAddNew_Execute()
        {
            Entity currentEntity = Entities.SelectedItem;
            if (currentEntity != null) 
            {
                Field newField = currentEntity.Fields.AddNew();
                newField.DataType = "varchar(32)";
                newField.Nullable = true;
                newField.PrimaryKey = false;
                newField.SortOrder = (byte?)((short)(from f in currentEntity.Fields select f.SortOrder).OrderByDescending(f => (f.HasValue ? f.Value : 0)).First() + 1);//(byte?)(currentEntity.Fields.Count());
                Fields.SelectedItem = newField;
            }
        }
    }
}
